package com.urbanski.clipboard.client.threads;

import java.util.Scanner;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import com.urbanski.clipboard.client.util.ClientConstants.ClientCommand;
import com.urbanski.clipboard.client.util.ClientUtils;
import com.urbanski.clipboard.common.exception.InvalidCommandException;
import com.urbanski.util.logging.LoggingUtil;

/*
 * User commands:
 * 
 * Quit
 * Join session
 * Leave session
 * Administer session
 * Change name
 * Pause session
 * Unpause session
 * Create session
 * Help
 * Connect
 * Disconnect
 */

public class ClientCommandLineListener implements Runnable
{
	private static final Logger LOGGER = Logger.getLogger(ClientCommandLineListener.class);

	public ClientCommandLineListener()
	{

	}

	@Override
	public void run()
	{
		LOGGER.trace("Entering CommandLineListener.run");

		LOGGER.info("Command line listener started");

		Scanner in = new Scanner(System.in);

		while (in.hasNextLine())
		{
			String line = in.nextLine();

			LOGGER.debug("Command entered: " + line);

			String[] tokens = StringUtils.split(line);

			try
			{
				ClientCommand command = ClientCommand.getClientCommand(tokens[0]);

				ClientUtils.processCommand(command, line, tokens);

				if (line.equals(ClientCommand.EXIT.getKeyword()))
				{
					break;
				}
			}
			catch (InvalidCommandException e)
			{
				LoggingUtil.logAndPrintError(LOGGER, e.getMessage());
			}
			catch (Exception e)
			{
				LOGGER.error("Unexpected exception occured in command line listener", e);
			}
		}

		in.close();

		LOGGER.info("Command line listener stopped");

		LOGGER.trace("Exiting CommandLineListener.run");
	}
}
